import { findRootElementById } from './bpmnPropertyUtils/eventDefinition'
import { getBusinessObject } from 'bpmn-js/lib/util/ModelUtil'
import { getExtensionElementsList, createModdleElement, addExtensionElements, removeExtensionElements } from './bpmnPropertyUtils/extensionElements'
import { useSettingStore } from '@/store/bpmnProcess/settingStore'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'

export const getErrors = (element) => {
  const prefix = useSettingStore().editor.processEngine
  const businessObject = getBusinessObject(element)
  return getExtensionElementsList(businessObject, `${prefix}:ErrorEventDefinition`)
}

export function addError(element, props) {
  const prefix = useSettingStore().editor.processEngine
  const modeling = useModelerStore().getModeling
  const businessObject = getBusinessObject(element)
  const errorEventDefinition = createModdleElement(`${prefix}:ErrorEventDefinition`, {}, undefined)
  const error = findRootElementById(businessObject, 'bpmn:Error', props.id)
  error.name = props.name
  error.errorCode = props.errorCode
  error.errorMessage = props.errorMessage
  modeling.updateModdleProperties(element, errorEventDefinition, { errorRef: error, [`${prefix}:expression`]: props.expression })
  addExtensionElements(element, businessObject, errorEventDefinition)
}

export function editError(element, error, props) {
  removeError(element, error)
  addError(element, props)
}

export function removeError(element, props) {
  const businessObject = getBusinessObject(element)
  removeExtensionElements(element, businessObject, props)
}
